// ==UserScript==
// @name           externalFuncButtonM.uc.js
// @description    External functions button
// @include        main
// @author         lastdream2013
// @charset        UTF-8
// @version        20130616.0.13 minor fix
// @version        20130511.0.11 tidy and merge moveable code
// @version        20130507 0.1 first release
// ==/UserScript==

var gExternalFuncButtonM = {
	autohideEmptySubDirs: true,  //自动隐藏没有一个子项目的子目录菜单
	moveSubDirstoBottom: false,  //把主菜单下的子目录移动到最下面
	moveablePositonOrInsertafter: false, //true : ToolbarPalette moveable button  false: insert appbutton in "insertafter" 
	insertafter: 'alltabs-button',  // useless if moveablePositonOrInsertafter is true;  urlbar-icons addon-bar TabsToolbar alltabs-button
	toolbar :
	{
		//在这里定义好主菜单下子目录的名字,以及图标  可在中间加{name: 'separator'}建立一个目录与目录之间的分隔线
		subdirs : [
			{
				name : 'firefox常用功能',
				image : ""
			},
			{
				name : 'about',
				image : ""
			},
		],

		//   在这里定义firefox的功能按钮, command就是一小段程序, 可以从firefox api, 小书签或鼠标手势中摘取;可选自定义图标;
		//    同样, 建议先写完上面想要定义, 分类在子目录下的程序,  之后从中摘出你最常用的, 去掉后面的subdir定义, 放在最下面
		configs : [
			{
				name : 'separator'
			},
			{
				name : 'about:firefox',
				subdir : 'about',
				command : "openAboutDialog();",
			},
			{
				name : 'about:about',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:about')",
			},
			{
				name : 'about:addons',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:addons')",
			},
			{
				name : 'about:cache',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:cache')",
			},
			{
				name : 'about:config',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:config')",
			},
			{
				name : 'about:memory',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:memory')",
			},
			{
				name : 'about:mozilla',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:mozilla')",
			},
			{
				name : 'about:plugins',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:plugins')",
			},
			{
				name : 'about:robots',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:robots')",
			},
			{
				name : 'about:support',
				subdir : 'about',
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:support')",
			},
			{
				name : '选项',
				subdir : 'firefox常用功能',
				image : "",
				command : "openPreferences();",
			},
			{
				name : '书签管理',
				subdir : 'firefox常用功能',
				image : "chrome://browser/skin/places/allBookmarks.png",
				command : "PlacesCommandHook.showPlacesOrganizer('AllBookmarks');",
			},
			{
				name : '历史',
				subdir : 'firefox常用功能',
				image : "chrome://browser/content/abouthome/history.png",
				command : "PlacesCommandHook.showPlacesOrganizer('History');",
			},
			{
				name : 'separator',
				subdir : 'firefox常用功能',
			},
			{
				name : '重启(清除启动缓存)',
				subdir : 'firefox常用功能',
				command : "Services.appinfo.invalidateCachesOnRestart() || Application.restart();",
			},

			// 建议把要放在子目录下的功能按钮,定义在上面, 下面的定义放在主菜单下的最常用的功能按钮,
			{
				name : '破解右键限制',
				subdir : '',
				image :"",
				command :
				function ()
				{
					gBrowser.loadURI("javascript:(function(){var%20doc=document;var%20bd=doc.body;bd.onselectstart=bd.oncopy=bd.onpaste=bd.onkeydown=bd.oncontextmenu=bd.onmousemove=bd.onselectstart=bd.ondragstart=doc.onselectstart=doc.oncopy=doc.onpaste=doc.onkeydown=doc.oncontextmenu=null;doc.onselectstart=doc.oncontextmenu=doc.onmousedown=doc.onkeydown=function%20(){return%20true;};with(document.wrappedJSObject||document){onmouseup=null;onmousedown=null;oncontextmenu=null;}var%20arAllElements=document.getElementsByTagName('*');for(var%20i=arAllElements.length-1;i&gt;=0;i--){var%20elmOne=arAllElements[i];with(elmOne.wrappedJSObject||elmOne){onmouseup=null;onmousedown=null;}}var%20head=document.getElementsByTagName('head')[0];if(head){var%20style=document.createElement('style');style.type='text/css';style.innerHTML=%22html,*{-moz-user-select:auto!important;}%22;head.appendChild(style);}void(0);})();")
				},
			},
			{
				name : '轻松下视频',
				subdir : '',
				image :"",
				command :
				function ()
				{
					gBrowser.loadURI("javascript:if(typeof%20yXzyxe58==typeof%20alert)yXzyxe58();window.open('http://www.youtubexia.com/?url='%20+encodeURIComponent(document.location.href),'getA','toolbar=no,%20location=no,%20directories=no,%20status=no,%20menubar=no,%20scrollbars=yes,%20resizable=yes,%20copyhistory=yes,%20width=800,%20height=600');void(0);")
				},
			},
			{
				name : 'PrintWhatYouLike',
				subdir : '',
				image :"",
				command :
				function ()
				{
					gBrowser.loadURI("javascript:(function(){if(window['ppw']&amp;&amp;ppw['bookmarklet']){ppw.bookmarklet.toggle();}else{window._pwyl_home='http://www.printwhatyoulike.com/';window._pwyl_pro_id=null;window._pwyl_bmkl=document.createElement('script');window._pwyl_bmkl.setAttribute('type','text/javascript');window._pwyl_bmkl.setAttribute('src',window._pwyl_home+'static/compressed/pwyl_bookmarklet_10.js');window._pwyl_bmkl.setAttribute('pwyl','true');document.getElementsByTagName('head')[0].appendChild(window._pwyl_bmkl);}})();")
				},
			},
			{
				name : '阅读助手',
				subdir : '',
				image :"",
				command :
				function ()
				{
					gBrowser.loadURI("javascript:(function(){readStyle='style-newspaper';readSize='size-large';readMargin='margin-wide';_readability_script=document.createElement('SCRIPT');_readability_script.type='text/javascript';_readability_script.src='http://lab.arc90.com/experiments/readability/js/readability.js?x='+(Math.random());document.getElementsByTagName('head')%5B0%5D.appendChild(_readability_script);_readability_css=document.createElement('LINK');_readability_css.rel='stylesheet';_readability_css.href='http://lab.arc90.com/experiments/readability/css/readability.css';_readability_css.type='text/css';_readability_css.media='screen';document.getElementsByTagName('head')%5B0%5D.appendChild(_readability_css);_readability_print_css=document.createElement('LINK');_readability_print_css.rel='stylesheet';_readability_print_css.href='http://lab.arc90.com/experiments/readability/css/readability-print.css';_readability_print_css.media='print';_readability_print_css.type='text/css';document.getElementsByTagName('head')%5B0%5D.appendChild(_readability_print_css);})();")
				},
			},
			{
				name : 'separator',
			},
			{
				name : '下载管理',
				image : "chrome://browser/skin/places/downloads.png",
				command : "BrowserDownloadsUI();",
			},
			{
				name : '附加组件',
				image : "chrome://mozapps/skin/extensions/extensionGeneric-16.png",
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:addons')",
			},
			{
				name : 'about:config',
				image : "",
				command : "getBrowser().selectedTab = getBrowser().addTab ('about:config')",
			},
			{
				name : '错误控制台',
				image : "",
				command : "toJavaScriptConsole();",
			},
		],
	},

	subdirPopupHash : [],
	subdirMenuHash : [],
	_externalFuncPopup : null,
	_isready : false,
	unescapeHTML : function(input) {
			return input.replace(/&amp;/g, '&')
		  .replace(/&quot;/g, '\"')
		  .replace(/&lt;/g, '<')
		  .replace(/&gt;/g, '>')
		  .replace(/&apos;/g, '\'')
		  .replace(/([^\\])\\([^\\])/g, '$1\\\\$2');
	},
	init : function () {

		// var ExternalFuncBtn = document.createElement('toolbarbutton');
		var ExternalFuncBtn = document.createElement('menu');
		ExternalFuncBtn.id = "ExternalFuncButtonM-ID";
		// ExternalFuncBtn.setAttribute("label", "扩展小功能按钮");
		ExternalFuncBtn.setAttribute("label", "扩展小功能");
		ExternalFuncBtn.setAttribute("class", "menu-iconic");
		ExternalFuncBtn.setAttribute("onclick", "event.preventDefault();event.stopPropagation();");
		ExternalFuncBtn.setAttribute("tooltiptext", "扩展小功能按钮,可以自定义小函数功能");
		// ExternalFuncBtn.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional");
		// ExternalFuncBtn.setAttribute("type", "menu");
		// ExternalFuncBtn.setAttribute("removable", "true");
		ExternalFuncBtn.setAttribute("image", "");

		var ExternalFuncPopup = document.createElement('menupopup');
		ExternalFuncPopup.setAttribute('onpopupshowing', 'event.stopPropagation();gExternalFuncButtonM.onpopupshowing();');
		this._externalFuncPopup = ExternalFuncPopup;
		ExternalFuncBtn.appendChild(ExternalFuncPopup);
		setTimeout(function () { //延时加载菜单，不对启动造成影响，也不影响第一次打开菜单时的响应速度
			gExternalFuncButtonM.loadSubMenu();
		}, 3000);

		var ins = document.getElementById("context-sharepage");
		ins.parentNode.insertBefore(ExternalFuncBtn, ins);

   //  	document.insertBefore(document.createProcessingInstruction('xml-stylesheet', 'type="text/css" href="data:text/css;utf-8,' + encodeURIComponent(
   //  	'\
			// #ExternalFuncButtonM-ID {\
			// -moz-appearance: none !important;\
			// border-style: none !important;\
			// border-radius: 0 !important;\
			// padding: 0 3px !important;\
			// margin: 0 !important;\
			// background: transparent !important;\
			// box-shadow: none !important;\
			// -moz-box-align: center !important;\
			// -moz-box-pack: center !important;\
			// min-width: 18px !important;\
			// min-height: 18px !important;\
			// }\
			// #ExternalFuncButtonM-ID > .toolbarbutton-icon {\
			// 	max-width: 18px !important;\
			// 	padding: 0 !important;\
			// 	margin: 0 !important;\
			// }\
			// #ExternalFuncButtonM-ID dropmarker{display: none !important;}\
   //  	') + '"'), document.documentElement);

		if (this.moveablePositonOrInsertafter) {
			var navigator = document.getElementById("navigator-toolbox");
			if (!navigator || navigator.palette.id !== "BrowserToolbarPalette")
				return;
			navigator.palette.appendChild(ExternalFuncBtn);
			this.updateToolbar();
		} else {
			var navigator = document.getElementById(this.insertafter);
			if (!navigator)
				return;
			navigator.parentNode.insertBefore(ExternalFuncBtn, navigator.previousSibling);
		}
	},
	loadSubMenu : function () {
		if (this._isready)
			return;
		if (this._externalFuncPopup == null)
			return;
		var ExternalFuncPopup = this._externalFuncPopup;
		for (var i = 0; i < this.toolbar.subdirs.length; i++) {
			if (this.toolbar.subdirs[i].name == 'separator') {
				ExternalFuncPopup.appendChild(document.createElement('menuseparator'));
			} else {
				var subDirItem = ExternalFuncPopup.appendChild(document.createElement('menu'));
				var subDirItemPopup = subDirItem.appendChild(document.createElement('menupopup'));
				subDirItem.setAttribute('class', 'menu-iconic');
				subDirItem.setAttribute('label', this.toolbar.subdirs[i].name);
				subDirItem.setAttribute('image', this.toolbar.subdirs[i].image);
				gExternalFuncButtonM.subdirPopupHash[this.toolbar.subdirs[i].name] = subDirItemPopup;
				gExternalFuncButtonM.subdirMenuHash[this.toolbar.subdirs[i].name] = subDirItem;
			}
		}

		for (var i = 0; i < this.toolbar.configs.length; i++) {
			var configItems;
			if (this.toolbar.configs[i].name == 'separator') {
				configItems = document.createElement('menuseparator');
			} else {
				configItems = ExternalFuncPopup.appendChild(document.createElement('menuitem'));
				configItems.setAttribute('class', 'menuitem-iconic');
				configItems.setAttribute('label', this.toolbar.configs[i].name);
				configItems.setAttribute('image', this.toolbar.configs[i].image);
				if (typeof this.toolbar.configs[i].command == 'function') {
					configItems.setAttribute('oncommand', this.unescapeHTML(this.toolbar.configs[i].command.toSource()) + '.call(this, event);');
				} else {
					configItems.setAttribute('oncommand', this.toolbar.configs[i].command);
				}
				configItems.setAttribute('tooltiptext', this.toolbar.configs[i].name);
			}
			if (this.toolbar.configs[i].subdir && gExternalFuncButtonM.subdirPopupHash[this.toolbar.configs[i].subdir])
				gExternalFuncButtonM.subdirPopupHash[this.toolbar.configs[i].subdir].appendChild(configItems);
			else
				ExternalFuncPopup.appendChild(configItems);
		}

		if (this.autohideEmptySubDirs) {
			for (let[name, popup]in Iterator(gExternalFuncButtonM.subdirPopupHash)) {
				if (popup.hasChildNodes()) {
					continue;
				} else {
					gExternalFuncButtonM.subdirMenuHash[name].setAttribute("hidden", "true");
				}
			}
		}

		if (this.moveSubDirstoBottom) {
			let i = ExternalFuncPopup.childNodes.length;
			while (ExternalFuncPopup.firstChild.getAttribute('class') != 'menuitem-iconic' && i-- != 0) {
				ExternalFuncPopup.appendChild(ExternalFuncPopup.firstChild);
			}
		}
		this._isready = true;
	},
	onpopupshowing : function () {
		if (!this._isready)
			this.loadSubMenu();
	},
	updateToolbar: function () {
		let toolbars = Array.slice(document.querySelectorAll('#navigator-toolbox > toolbar'));
		toolbars.forEach(function (toolbar) {
			var currentset = toolbar.getAttribute("currentset");
			if (currentset.split(",").indexOf("ExternalFuncButtonM-ID") < 0)
				return;
			toolbar.currentSet = currentset;
			try {
				BrowserToolboxCustomizeDone(true);
			} catch (ex) {}
		});
	}
};

    gExternalFuncButtonM.init();